﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Autofac;
using System.Data.Entity;
using Simple.EF;
using Simple.Common.Data;
using System.Reflection;
using Autofac.Integration.Mvc;
using Simple.Service;

using Simple.Common.Infrastructure.DependencyManagement;
using Simple.Common.Caching;
using Simple.Services.Events;

namespace Simple.Web.Framework
{
    public class DependencyRegistrar : IDependencyRegistrar
    {
        public void Register(ContainerBuilder builder, Simple.Common.Infrastructure.ITypeFinder typeFinder)
        {
            Type typeWorkEfDbContext = typeof(WorkEfDbContext);
            builder.RegisterType(typeWorkEfDbContext).AsSelf().InstancePerLifetimeScope();

            Type typeWorkEfRepository = typeof(WorkEfRepository<>);
            builder.RegisterGeneric(typeWorkEfRepository).AsSelf().InstancePerLifetimeScope();
            builder.RegisterControllers(typeFinder.GetAssemblies().ToArray());
            builder.RegisterFilterProvider();

            Type typeapplicationService = typeof(ApplicationService);
            builder.RegisterTypes(typeapplicationService.Assembly.GetTypes()).Where(m => m.BaseType.Name == "ApplicationService").AsSelf().InstancePerLifetimeScope();
            //cache manager
            builder.RegisterType<MemoryCacheManager>().As<ICacheManager>().Named<ICacheManager>("simple_cache_static").SingleInstance();
            //Register event consumers
            var consumers = typeFinder.FindClassesOfType(typeof(IConsumer<>)).ToList();
            foreach (var consumer in consumers)
            {
                builder.RegisterType(consumer)
                    .As(consumer.FindInterfaces((type, criteria) =>
                    {
                        var isMatch = type.IsGenericType && ((Type)criteria).IsAssignableFrom(type.GetGenericTypeDefinition());
                        return isMatch;
                    }, typeof(IConsumer<>)))
                    .InstancePerLifetimeScope();
            }
           // builder.RegisterType<EventPublisher>().As<IEventPublisher>().SingleInstance();
           // builder.RegisterType<SubscriptionService>().As<ISubscriptionService>().SingleInstance();
        }

        public int Order
        {
            get { return 0; }
        }
    }
}